import { Product, ProductService } from "@mallfoundry/catalog"
import { message as antMessage, PageHeader } from "antd"
import * as React from "react"
import { useState } from "react"
import { useParams } from "react-router-dom"
import Page from "../../components/page"
import { useProduct } from "../../hooks/product"
import { messageError } from "../../utils/reason"

import classes from "./product-edit.module.scss"
import ProductForm from "./product-form"

export default function ProductEdit() {
  const { productId = "" } = useParams<{ productId: string }>()
  const { loading, product } = useProduct(productId)
  const [updatedLoading, setUpdateLoading] = useState(false)

  function onFinish(newProduct: Product) {
    setUpdateLoading(true)
    ProductService.updateProduct(newProduct)
      .then(() => {
        antMessage.success("保存成功")
      })
      .catch(messageError)
      .finally(() => setUpdateLoading(false))
  }

  return (
    <div className={classes.editProduct}>
      <PageHeader title="编辑商品" ghost={false}/>
      <Page.Content loading={loading}>
        <ProductForm loading={loading || updatedLoading} product={product} onFinish={onFinish}/>
      </Page.Content>
    </div>
  )

}
